const express = require('express');
const router = express.Router();
const StrategyService = require('../services/StrategyService');
const { authenticateToken } = require('../middleware/auth');

// 创建策略 (需要认证)
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { name, description, config } = req.body;
    const userId = req.user.id;

    const strategy = await StrategyService.createStrategy(userId, name, description, config);
    
    res.status(201).json({
      success: true,
      data: strategy
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 获取用户的所有策略 (需要认证)
router.get('/', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const strategies = await StrategyService.getStrategiesByUserId(userId);
    
    res.json({
      success: true,
      data: strategies
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 获取特定策略 (需要认证)
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    // 验证用户是否有权访问此策略
    const strategy = await StrategyService.getStrategyById(id);
    
    if (strategy.user_id !== userId) {
      return res.status(403).json({
        success: false,
        error: 'Access denied'
      });
    }
    
    res.json({
      success: true,
      data: strategy
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 更新策略 (需要认证)
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, config, is_active } = req.body;
    const userId = req.user.id;
    
    // 验证用户是否有权更新此策略
    const existingStrategy = await StrategyService.getStrategyById(id);
    
    if (existingStrategy.user_id !== userId) {
      return res.status(403).json({
        success: false,
        error: 'Access denied'
      });
    }
    
    const strategy = await StrategyService.updateStrategy(id, name, description, config, is_active);
    
    res.json({
      success: true,
      data: strategy
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 删除策略 (需要认证)
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    // 验证用户是否有权删除此策略
    const strategy = await StrategyService.getStrategyById(id);
    
    if (strategy.user_id !== userId) {
      return res.status(403).json({
        success: false,
        error: 'Access denied'
      });
    }
    
    await StrategyService.deleteStrategy(id);
    
    res.json({
      success: true,
      message: 'Strategy deleted successfully'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 执行移动平均线策略
router.post('/execute/ma', authenticateToken, async (req, res) => {
  try {
    const { symbol, shortPeriod, longPeriod } = req.body;
    console.log("-执行ma-->",req.body)
    const userId = req.user.id;
    
    if (!symbol) {
      return res.status(400).json({
        success: false,
        error: 'Symbol is required'
      });
    }
    
    const result = await StrategyService.executeMovingAverageStrategy(
      userId, 
      symbol, 
      shortPeriod, 
      longPeriod
    );
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.log("---执行ma失败--->",error)
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 执行RSI策略
router.post('/execute/rsi', authenticateToken, async (req, res) => {
  try {
    const { symbol, period, overbought, oversold } = req.body;
    const userId = req.user.id;
    
    if (!symbol) {
      return res.status(400).json({
        success: false,
        error: 'Symbol is required'
      });
    }
    
    const result = await StrategyService.executeRSIStrategy(
      symbol, 
      period, 
      overbought, 
      oversold
    );
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 在 strategies.js 中添加
router.post('/execute/bb', authenticateToken, async (req, res) => {
  try {
    const { symbol, period, multiplier } = req.body;
    const userId = req.user.id;
    
    if (!symbol) {
      return res.status(400).json({
        success: false,
        error: 'Symbol is required'
      });
    }
    
    const result = await StrategyService.executeBollingerBandsStrategy(
      symbol, 
      period, 
      multiplier
    );
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 执行海龟交易策略
router.post('/execute/turtle', authenticateToken, async (req, res) => {
  try {
    const { symbol, entryPeriod, exitPeriod } = req.body;
    const userId = req.user.id;
    
    if (!symbol) {
      return res.status(400).json({
        success: false,
        error: 'Symbol is required'
      });
    }
    
    const result = await StrategyService.executeTurtleTradingStrategy(
      symbol, 
      entryPeriod, 
      exitPeriod
    );
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 执行多因子选股策略
router.post('/execute/multi-factor', authenticateToken, async (req, res) => {
  try {
    const { symbols, factorWeights, topN } = req.body;
    const userId = req.user.id;
    
    if (!symbols || !Array.isArray(symbols)) {
      return res.status(400).json({
        success: false,
        error: 'Symbols array is required'
      });
    }
    
    if (!factorWeights || typeof factorWeights !== 'object') {
      return res.status(400).json({
        success: false,
        error: 'Factor weights object is required'
      });
    }
    
    const result = await StrategyService.executeMultiFactorStrategy(
      symbols, 
      factorWeights, 
      topN || 10
    );
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;